<#import "inc/macro-page.html" as panel>
<#import "macro-filter-card-box.html" as seachpanel>
<#escape x as x?html>
<@panel.header "中青年龄结构预警" "">
</@panel.header>
<@panel.body>
            <!-- Bread crumb -->
            <div class="row page-titles">
                <div class="col-md-5 align-self-center">
                    <h3>中青年龄结构预警</h3>
                </div>
                <div class="col-md-7 align-self-center">&nbsp;</div>
            </div>
            <!-- End Bread crumb -->
            <!-- Container fluid  -->
            <div class="container-fluid">
                <!-- Start Page Content --> 
                <div class="card">
					<div class="custom-card-header quick-bar">
						<div class="hint">&nbsp;</div>
					    <@seachpanel.filterbox></@seachpanel.filterbox>
					    <button id="id-export-file" type="button" class="btn btn-dark btn-outline btn-sm m-l-10" title="导出"><i class="fa fa-share-square-o"></i></button>
					</div>                	
                     
                    <div class="card-body">
		                  <div id="id-diagram-group" class="row m-t-20">
		                  	<div class="col-lg-12">
		                  		<div id="id-young-chart" style="height: 480px"></div>
		                  		<table id="id-young-table" class="table table-bordered table-cell-wrap m-t-40"  cellspacing="0" width="100%"></table>		                  		
		                  	</div>
		                  </div>
                    </div>
                </div>
               	<!-- End PAge Content -->
            </div>
            <!-- End Container fluid  -->
</@panel.body>
<@panel.footer>
<script type="text/javascript" src="${ROOT}/mind/js/plugins/alangyun-filterbox.js"></script>
<script type="text/javascript" src="${ROOT}/mind/js/lib/datatables/datatables.min.js"></script>
<script type="text/javascript" src="${ROOT}/mind/js/lib/datatables/jquery.dataTables.zh-CN.js"></script>
<script type="text/javascript" src="${ROOT}/mind/js/lib/echart/echarts.min.5.4.0.js"></script>
<script type="text/javascript">
    // word导出事件
    document.getElementById('id-export-file').addEventListener('click', function() {
        // Ensure echarts charts have finished rendering
        setTimeout(() => {
            var charts = document.querySelectorAll('canvas');
            charts.forEach(chart => {
                var dataURL = chart.toDataURL();
                var imgTag = '<img src="' + dataURL + '" width="700" />';
                chart.insertAdjacentHTML('beforebegin', imgTag);
                chart.style.display = 'none'; // Hide the original canvas
            });

            // Create a temporary container for the export
            var exportContainer = document.createElement('div');
            exportContainer.id = 'export-container';
            exportContainer.style.width = '100%';

            // Clone ECharts charts
            var chartContainer = document.getElementById('id-young-chart').cloneNode(true);
            exportContainer.appendChild(chartContainer);

            // Clone user table and add border class

            var clonedTable = document.getElementById('id-young-table').cloneNode(true);
// 直接添加内联样式到每个th和td元素
            clonedTable.querySelectorAll('th, td').forEach(function(cell) {
                cell.style.border = '1px solid #000';
                cell.style.borderCollapse = 'collapse'; // 注意：borderCollapse是CSS属性，不能作为内联样式设置，但这里为了示例而写
                cell.style.textAlign = 'center';
            });
            exportContainer.appendChild(clonedTable);

            // Convert the export container's HTML to a Word document
            var htmlHeader = `
          <!DOCTYPE html>
          <html>
          <head>
            <style>
               table, th, td {
                   border: 1px solid #000;
                   text-align: center;
                   border-collapse: collapse;
               }
            </style>
          </head>
          <body>`;
            var htmlFooter = `
          </body>
          </html>`;
            var htmlContent = htmlHeader + exportContainer.innerHTML + htmlFooter;

            var blob = new Blob([htmlContent], { type: 'application/msword' });
            var url = URL.createObjectURL(blob);
            var a = document.createElement('a');
            a.href = url;
            a.download = '中青年龄结构预警.doc';
            a.click();
            URL.revokeObjectURL(url);

            // Clean up by removing the temporary container
            exportContainer.remove();

            // Revert changes made to the document for export
            charts.forEach(chart => {
                chart.previousSibling && chart.previousSibling.remove();
                chart.style.display = 'block'; // Restore the original canvas
            });
        }, 1000); // Adjust the timeout as needed to ensure charts have rendered
    });
$(document).ready(function(){
	
	$(".btn-click-bind").click(function() {
		  var val = $(this).data("sign");
		  var ctx = "/t/team";
		  if(12===val){
			  ctx = "/t/team12";
		  } else if(13===val){
			  ctx="/t/team13"
		  } else if(14===val){
			  ctx="/t/team14"
		  }
		  window.location.href="${ROOT}" + ctx;
	});	
	
	//最新下载的数据
	var currentData = null;

    var chatYoung = echarts.init(document.getElementById("id-young-chart"), null, {
      renderer: 'canvas',
      useDirtyRect: false
    });
    window.addEventListener('resize', chatYoung.resize);
	
	var convertDataToView =function(svrData){
		var ret ={
				columns:[],
				chatData:{},
				chatSum:{},
				years:[],
				tableCol: [],
				tableData:{}
		}
		var loadCol= false;
		ret.tableCol.push({
			"title":"",
			"mData": "name",
			"sClass": "cell-no-wrap"
		})
		svrData.forEach(item=>{
			var l = item.year+"";
			ret.years.push(l);
			ret.chatData[l]=[];
			ret.tableData[l]=[];
			var col = 0; var sum=0;
			var cdata = {'name':'数量'}, rdata={'name':'占比'};
			item.ages.forEach(age=>{
				if(!loadCol){
					ret.columns.push(age.name);
					ret.tableCol.push({
						"title": age.name,
						"mData": 'col'+col,
						"defaultContent": ''
					});
				}
				ret.chatData[l].push(age.count);
				sum+=age.count;
				
				cdata['col'+ col]= age.count;
				rdata['col'+(col++)] = age.percent;
			})
			ret.chatSum[l]=sum;
			ret.tableData[l].push(cdata);
			ret.tableData[l].push(rdata);
			
			loadCol= true;
		})
		
		return ret;
	}

	var $table = null;
	var dataToTableView = function(index){
		if(!currentData){
			return;
		}
		
		var key = currentData.years[index];
		
		if($table) {
			$table.fnClearTable();
			$table.fnDestroy();
		}
		
		$table = $("#id-young-table").dataTable({
		    "ordering":false,
		    "searching": false,
		    "bFilter":false,
		    "info": false,
		    "paging": false,
		    'bAutoWidth':false,
		    "bDestroy" : true,
		    "aoColumns": currentData.tableCol,	
		    "data":currentData.tableData[key]
		});
		$table.fnDraw();
	};
	
	//分析图
	var dataToChartView = function(){
		if(!currentData){
			return;
		}

	    var myseries=[];
	    currentData.years.forEach(name=>{
	    	myseries.push({
		      title: { text: name+"年中青年年龄结构", left:'center' },
		      colorBy: 'data',
		      color: ['#007470','#00c4c0','#00c4c0','#007470','#00c4c0','#00c4c0','#00c4c0','#007470','#00c4c0','#00c4c0'],
		      series: [
		        { 
		        	data: currentData.chatData[name],
	                label: {
	                	show: true,
	                	position: 'top'
	                }
		        },
		        {
		          data: [
		            { name: '人数', value: currentData.chatSum[name] }
		          ]
		        }
		      ]
	    	})
	    });	    
	    
	    var option = {
		  baseOption: {
		    timeline: {
		      axisType: 'category',
		      checkpointStyle:{symbol:'rect', borderWidth: 0},
		      /* controlStyle:{show: false}, */
		      autoPlay: false,
		      playInterval: 2000,
		      data: currentData.years,
		      label: {
		        formatter: function (s) {
		          return s + "年";
		        }
		      }
		    },
		    tooltip: {},
		    calculable: true,
		    grid: {
		      top: 80,
		      bottom: 120,
		      tooltip: {
		        trigger: 'axis',
		        axisPointer: {
		          type: 'shadow',
		          label: {
		            show: true
		          }
		        }
		      }
		    },
		    xAxis: [
		      {
		        type: 'category',
		        axisLabel: { interval: 0 },
		        data: currentData.columns,
		        splitLine: { show: false }
		      }
		    ],
		    yAxis: [
		      {
		        type: 'value'
		      }
		    ],
		    series: [
		      { name: '人数', type: 'bar' }
		    ]
		  },
		  options: myseries
		};
	    
	    if (option && typeof option === 'object') {
	    	chatYoung.setOption(option);
	    }

	}

    chatYoung.on("timelinechanged", function(selection){
    	dataToTableView(selection.currentIndex);
    });

    // 导出事件绑定
    // $('#id-export-file').click(function(){
    // 	var pdfCanvas = $.fn.pdfcanvas({
    // 		title: '中青年龄结构预警',
    // 		keywords: '单位和部门：；岗位类别：'
    // 	})
    // 	pdfCanvas.addDom(document.getElementById("id-diagram-group"));
    // 	pdfCanvas.print();
    //
    // });
    
    //初始化过滤面板
    $.post('${ROOT}/t/treeNav',function(data, status){
    	if(data.code==="ok"){
			$.fn.filterBox({
				data: data.data,
				onsubmit: function(form, data){
				    $.post('${ROOT}/t/sumyoung',data,function(data, status){
				    	if(data.code==="ok"){
				    		if( data.data){
					    		currentData= convertDataToView(data.data);
					    		dataToChartView();
					    		dataToTableView(0);
					    	}else{
					    		toastr.error("未找到任何预警资料");
					    	}
				    	}else {
				    		toastr.error(data.desc);
				    	}
				    }, 'json');
				}
			})
    	}
    })

    //先提取数据
    $.post('${ROOT}/t/sumyoung',function(data, status){
    	if(data.code==="ok"){
    		if( data.data){
	    		currentData= convertDataToView(data.data);
	    		dataToChartView();
	    		dataToTableView(0);
	    	}else{
	    		toastr.error("未找到任何预警资料");
	    	}
    	}else {
    		toastr.error(data.desc);
    	}
    }, 'json');
});
</script>
</@panel.footer>
</#escape>
